package com.smsc.headend.task.engine.handler.impl.ansi;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.SystemClock;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.emeter.energyip.amiinterface.MeterReadsReplyMessageDocument;
import com.smsc.headend.common.enums.DeviceType;
import com.smsc.headend.common.enums.errorcode.TaskHandlerErrorCode;
import com.smsc.headend.common.utils.ProtoBufferUtil;
import com.smsc.headend.common.utils.RedisUtils;
import com.smsc.headend.module.asset.entity.Meter;
import com.smsc.headend.module.data.dto.TaskDataDTO;
import com.smsc.headend.module.data.dto.TaskPacketDTO;
import com.smsc.headend.module.event.entity.RdEventMeter;
import com.smsc.headend.module.protocol.DeviceData;
import com.smsc.headend.module.protocol.ansi.AnsiByteBuffer;
import com.smsc.headend.module.protocol.ansi.AnsiData;
import com.smsc.headend.module.report.entity.LogScheduleTaskDevice;
import com.smsc.headend.module.task.consts.TaskKafkaTopic;
import com.smsc.headend.module.task.dto.AtomicTask;
import com.smsc.headend.module.task.dto.Task;
import com.smsc.headend.module.task.dto.TaskEventData;
import com.smsc.headend.module.task.dto.TaskResult;
import com.smsc.headend.module.task.enums.TaskType;
import com.smsc.headend.module.task.proto.TaskEventDataProto;
import com.smsc.headend.task.engine.dao.TaskDAO;
import com.smsc.headend.task.engine.exception.UDISTaskHandlerException;
import com.smsc.headend.task.engine.handler.TaskHandler;
import com.smsc.headend.task.engine.service.CollMeterTaskPlanService;
import com.smsc.headend.task.engine.service.CosemXmlService;
import com.smsc.headend.task.engine.service.DataProcessService;
import com.smsc.headend.task.engine.service.FeignAssetManagementService;
import com.smsc.headend.task.engine.service.asset.AssetService;
import com.smsc.headend.task.engine.service.push.EventService;
import com.smsc.headend.task.engine.service.task.LogScheduleTaskDeviceService;
import com.smsc.headend.task.engine.service.task.impl.TaskServiceImpl;
import com.smsc.headend.task.engine.utils.DdsXmlGenerateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author liangli
 * @date 2020/11/12
 */
@Slf4j
public class ReadAnsiEdModeHandler implements TaskHandler {
    @Autowired
    FeignAssetManagementService assetManagementService;
    @Autowired
    AssetService assetService;
    @Autowired
    CosemXmlService cosemXmlService;
    @Autowired
    KafkaTemplate kafkaTemplate;
    @Autowired
    EventService eventService;
    @Autowired
    DataProcessService dataProcessService;
    @Autowired
    TaskDAO taskDAO;
    @Autowired
    TaskServiceImpl taskService;
    @Autowired
    CollMeterTaskPlanService collMeterTaskPlanService;
    @Autowired
    DdsXmlGenerateUtil ddsXmlGenerateUtil;
    @Autowired
    LogScheduleTaskDeviceService logScheduleTaskDeviceService;
    @Autowired
    RedisUtils redisUtils;

    @Override
    public int handle(Task task, AtomicTask atomicTask, DeviceData deviceData, String actionResult) throws UDISTaskHandlerException {
        if (!(deviceData instanceof AnsiData)) {
            throw new UDISTaskHandlerException(TaskHandlerErrorCode.DEVICE_DATA_TYPE_NOT_SUPPORT.toString());
        }
        log.debug("the ed mode status : {}", deviceData);
        AnsiData data = (AnsiData) deviceData;
        AnsiByteBuffer ansiByteBuffer = data.getAnsiByteBuffer();
        Meter meter = assetService.getMeterById(task.getMeterId());
        List<RdEventMeter> allEvent = new ArrayList<>();
        Map<String, Object> param = JSONUtil.toBean(atomicTask.getAtomicTaskParam(), Map.class);
        Long lbDataItemId = Long.valueOf(String.valueOf(param.get("dataItemId")));
        Long lbTemplateId = param.get("lbTemplateId") != null ? Long.valueOf(String.valueOf(param.get("lbTemplateId"))) : null;
        if (lbTemplateId == null) {
            throw new UDISTaskHandlerException(TaskHandlerErrorCode.NO_LB_TEMPLATE_ID.toString());
        }
        // 00 00 06 01 00 00 00 C1 80 BE
        int byteIndex;
        int bitIndex;
        long now = SystemClock.now() / 1000;
        for (int eventCode = 8; eventCode < 48; eventCode++) {
            byteIndex = eventCode / 8 + 3;
            bitIndex = eventCode % 8;
            if (isBitTrue(ansiByteBuffer, byteIndex, bitIndex)) {
                Integer eventType = eventService.getTaskEventType(task, eventCode, lbDataItemId, DeviceType.METER.getId());
                if(eventType == null) {
                    continue;
                }
                RdEventMeter rdEventMeter = new RdEventMeter();
                rdEventMeter.setMeterId(task.getMeterId());
                rdEventMeter.setLbDataItemId(lbDataItemId);
                rdEventMeter.setTv(now);
                rdEventMeter.setEventType(eventType);
                rdEventMeter.setEventCode(eventCode);
                rdEventMeter.setEventName(eventService.getEventName(Convert.toLong(eventType)));
                rdEventMeter.setReceiveType(2);
                rdEventMeter.setTvUpdate(now);
                allEvent.add(rdEventMeter);
            }
        }
        handleEvent(task, atomicTask, meter, allEvent, lbDataItemId);

        return 1;
    }

    private static boolean isBitTrue(AnsiByteBuffer ansiByteBuffer, int byteIndex, int bitIndex) {
        return (ansiByteBuffer.getUInt8(byteIndex) >> bitIndex & 1) == 1;
    }

    private void handleEvent(Task task, AtomicTask atomicTask, Meter meter, List<RdEventMeter> allEvent, Long lbDataItemId) {
        TaskEventData readData = new TaskEventData();
        readData.setRdEventMeter(allEvent);
        readData.setLbDataItemId(lbDataItemId);
        readData.setTaskNo(task.getTaskNo());
        readData.setIsODR(task.getIsODR());
        readData.setDeviceId(task.getMeterId());
        readData.setDeviceType(DeviceType.METER.getId());
        if (allEvent.size() > 0) {
            kafkaTemplate.send(TaskKafkaTopic.DEVICE_EVENT_TRANSFER, ProtoBufferUtil.toProtoBuffer(readData, TaskEventDataProto.TaskEventData.class).toByteArray());
            if (TaskType.EventRead_Profile.toString().equalsIgnoreCase(task.getTaskType())) {
                logScheduleTaskDeviceService.sendMessage(task, LogScheduleTaskDevice.StatusEnum.Success.getCode(), LogScheduleTaskDevice.StatusDescEnum.CollectedSuccess.getCode());
            }
        } else {
            if (TaskType.EventRead_Profile.toString().equalsIgnoreCase(task.getTaskType())) {
                logScheduleTaskDeviceService.sendMessage(task, LogScheduleTaskDevice.StatusEnum.Failed.getCode(), LogScheduleTaskDevice.StatusDescEnum.EmptyData.getCode());
            }
        }
//        eventService.saveLogbookReadResult(readData, task.getMeterId());
        if (task.getIsODR()) {
            taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), lbDataItemId.toString(), JSONUtil.toJsonStr(allEvent), Long.valueOf(1 * 60 * 60), true);
        }
        if (TaskType.EventRead_Profile.toString().equalsIgnoreCase(task.getTaskType())) {
            collMeterTaskPlanService.saveMeterCollectProgress(SystemClock.now() / 1000, task.getMeterId(), lbDataItemId);
        }
        if (StrUtil.equalsIgnoreCase(task.getTaskType(), TaskType.Interface_ODR_LogBook.name()) || StrUtil.equalsIgnoreCase(task.getTaskType(), TaskType.UAA_MeterReads.name())) {
            taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), lbDataItemId.toString(), allEvent.size() > 0 ? JSONUtil.toJsonStr(allEvent) : "no data", Long.valueOf(1 * 60 * 60), true);
            // UAA接口的随抄执行成功要返回给 WF MDM
            List<TaskPacketDTO> taskPacketDTOList = taskService.getTaskPacket(task.getTaskNo());
//            if (CollectionUtil.isNotEmpty(taskPacketDTOList)){
            log.debug("Interface_ODR_LogBook packet result are: {}", JSONUtil.toJsonStr(taskPacketDTOList));


            TaskResult taskResult = new TaskResult();
            taskResult.setMessageId(task.getMessageId());
            taskResult.setTaskNo(task.getTaskNo());
            taskResult.setResultData(readData);

            Map<String, Object> dataItemMap = JSONUtil.toBean(atomicTask.getAtomicTaskParam(), Map.class);
            Map<String, Object> taskResultMap = JSONUtil.toBean(task.getParamJson(), Map.class);
            taskResultMap.putAll(dataItemMap);

            taskResultMap.put("packets", taskPacketDTOList);
            taskResultMap.put("meterModelId", meter.getModelId());
            taskResultMap.put("meterCustomSn", meter.getCustomerSn());
            taskResultMap.put("profileDataItemId", lbDataItemId);
            taskResult.setParamJson(JSONUtil.toJsonStr(taskResultMap));
            if (isTaskLastAtomicTask(task, atomicTask)) {
                List<TaskDataDTO> taskDataDTOS = taskDAO.getAllTaskData(task.getTaskNo());
                List<RdEventMeter> currentRdEventMeters = new ArrayList<>();
                for (TaskDataDTO taskDataDTO : taskDataDTOS) {
                    Object value = taskDataDTO.getValue();
                    String rdStr = (String) value;
                    if (!"no data".equals(rdStr)) {
                        List<RdEventMeter> rdEventMeters = JSONUtil.toList(rdStr, RdEventMeter.class);
                        currentRdEventMeters.addAll(rdEventMeters);
                    }
                }
                MeterReadsReplyMessageDocument document = null;
                if (CollectionUtil.isNotEmpty(currentRdEventMeters)) {
                    document = ddsXmlGenerateUtil.getDocumentEvent(Arrays.asList(readData));
                } else {
                    document = MeterReadsReplyMessageDocument.Factory.newInstance();
                }
                taskResult.setDocumentData(document.toString());
            }
            kafkaTemplate.send(TaskKafkaTopic.TASK_COMPLETE_RESULT_FROM_UTE_TO_ADAPTER, JSONUtil.toJsonStr(taskResult).getBytes(Charset.forName("utf-8")));
//            } else {
//                log.error("odr logBook Profile Data reply without packets! taskNo: {}", task.getTaskNo());
//            }
        }
    }

    @Override
    public int handleFailure(Task task, AtomicTask atomicTask, String message) {
        log.info("error {}, ", message);
        if (task.getIsODR()) {
            Map<String, Object> param = getParameterMap(task, atomicTask);
            Long lbDataItemId = Long.valueOf(String.valueOf(param.get("dataItemId")));
            // key 回曲线的dataItemId给web
            taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), Convert.toStr(lbDataItemId), message, 3600l, false);
        }
        if (StrUtil.equalsIgnoreCase(task.getTaskType(), TaskType.Interface_ODR_LogBook.name()) || StrUtil.equalsIgnoreCase(task.getTaskType(), TaskType.UAA_MeterReads.name())) {
            // UAA接口的随抄执行失败也要返回给 WF MDM
            TaskResult taskResult = new TaskResult();
            taskResult.setMessageId(task.getMessageId());
            taskResult.setTaskNo(task.getTaskNo());
            taskResult.setExceptionCause(message);
            Map<String, Object> dataItemMap = getParameterMap(task, atomicTask);
            Map<String, Object> taskResultMap = JSONUtil.toBean(task.getParamJson(), Map.class);
            taskResultMap.putAll(dataItemMap);
            Meter meter = assetService.getMeterById(task.getMeterId());
            Long lbDataItemId = Long.valueOf(String.valueOf(dataItemMap.get("dataItemId")));
            List<TaskPacketDTO> taskPacketDTOList = taskService.getTaskPacket(task.getTaskNo());
            if (CollectionUtil.isNotEmpty(taskPacketDTOList)) {
                taskResultMap.put("packets", taskPacketDTOList);
            }
            taskResultMap.put("meterModelId", meter.getModelId());
            taskResultMap.put("meterCustomSn", meter.getCustomerSn());
            taskResultMap.put("profileDataItemId", lbDataItemId);
            taskResult.setExceptionCause(message);
            taskResult.setParamJson(JSONUtil.toJsonStr(taskResultMap));
            kafkaTemplate.send(TaskKafkaTopic.TASK_COMPLETE_RESULT_FROM_UTE_TO_ADAPTER, JSONUtil.toJsonStr(taskResult).getBytes(Charset.forName("utf-8")));
        }
        if (StrUtil.equalsIgnoreCase(task.getTaskType(), TaskType.EventRead_Profile.name())) {
            logScheduleTaskDeviceService.sendMessage(task, LogScheduleTaskDevice.StatusEnum.Failed.getCode(), LogScheduleTaskDevice.StatusDescEnum.DecodeDataFailed.getCode());
        }
        return -1;
    }
}
